package graph;

import java.util.ArrayList;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-10-23
 * Time:22:59
 */
public class GraphByNode {
    static class Node {
        public int src;//起始位置
        public int dest;//目标位置
        public int weight;
        public Node next;

        public Node(int src, int dest, int weight) {
            this.src = src;
            this.dest = dest;
            this.weight = weight;
        }
    }

    public char[] arrayV;
    public ArrayList<Node> edgList;//存储边
    public boolean isDirect;

    public GraphByNode(int size, boolean isDirect) {
        this.arrayV = new char[size];
        edgList = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            edgList.add(null);//初始化
        }
        this.isDirect = isDirect;
    }

    /**
     * 初始化顶点数组
     * @param array
     */
    public void initArrayV(char[] array) {
        for (int i = 0; i < array.length; i++) {
            arrayV[i] = array[i];
        }
    }

    public void addEdge(char srcV, char destV, int weight) {
        int srcIndex = getIndexOfV(srcV);
        int destIndex = getIndexOfV(destV);
        addEdgeChild(srcIndex, destIndex, weight);

    }

    private void addEdgeChild(int srcIndex, int destIndex, int weight) {
        Node cur = edgList.get(srcIndex);
        while (cur != null) {
            if (cur.dest == destIndex) {
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(srcIndex, destIndex, weight);
        node.next = edgList.get(srcIndex);
        edgList.set(srcIndex,node);
    }

    private int getIndexOfV(char v) {
        for (int i = 0; i < arrayV.length; i++) {
            if (arrayV[i] == v) {
                return i;
            }
        }
        return -1;
    }

    public void printGraph() {
        for (int i = 0; i < arrayV.length; i++) {
            System.out.println(arrayV[i]+"->");
            Node cur = edgList.get(i);
            while (cur != null) {
                System.out.println(arrayV[cur.dest] + "->");
                cur = cur.next;
            }
            System.out.println();
        }
    }

}
